package gui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import network.AddNewUserMsg;
import network.AuthenticateUserMsg;
import network.Client;
import network.ErrorMsg;
import network.NetworkMsg;
import network.Type;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import com.swtdesigner.SWTResourceManager;

public class UserLogin extends Dialog {
	private Text txtEmail;
	private boolean newUser=false;
	private Label usernameLabel;
	private Label passwordLabel;
	private Label retypePasswordLabel;
	private Label emailLabel;
	private Text txtUsername;
	private Text txtPassword;
	private Text txtRetypePassword;
	private Shell shell;
	private RiskGUI window;
	/**
	 * Create the dialog
	 * @param parentShell
	 */
	public UserLogin(Shell parentShell, RiskGUI window) {
		super(parentShell);
		shell=parentShell;
		this.window=window;
	}

	/**
	 * Create contents of the dialog
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		container.setLayout(gridLayout);

		usernameLabel = new Label(container, SWT.NONE);
		final GridData gd_usernameLabel = new GridData();
		usernameLabel.setLayoutData(gd_usernameLabel);
		usernameLabel.setText("Username:");

		txtUsername = new Text(container, SWT.BORDER);
		txtUsername.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		passwordLabel = new Label(container, SWT.NONE);
		passwordLabel.setText("Password:");

		txtPassword = new Text(container, SWT.BORDER | SWT.PASSWORD);
		txtPassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		if (RiskGUI.getUsername()!=null){
			txtUsername.setText(RiskGUI.getUsername());
			txtPassword.setFocus();
		}
		retypePasswordLabel = new Label(container, SWT.NONE);
		retypePasswordLabel.setText("Retype Password:");
		retypePasswordLabel.setVisible(false);
		txtRetypePassword = new Text(container, SWT.BORDER | SWT.PASSWORD);
		txtRetypePassword.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
		txtRetypePassword.setVisible(false);

		emailLabel = new Label(container, SWT.NONE);
		emailLabel.setText("Email:");
		emailLabel.setVisible(false);
		txtEmail = new Text(container, SWT.BORDER);
		txtEmail.addFocusListener(new FocusAdapter() {
			public void focusLost(final FocusEvent arg0) {
				//Checks for email addresses starting with
				//inappropriate symbols like dots or @ signs.
				if  (txtEmail.getText().length()!=0){
					boolean correct=true;
					Pattern p = Pattern.compile("^\\.|^\\@");
				    Matcher m = p.matcher(txtEmail.getText());
				    if (m.find()){
				    	String str="Email addresses don't start with dots or @ signs.";
				    	AutoDialogMessegaes.displayErrorMsg("Email", str, shell);
				    	correct=false;
				    }else
				    	correct=true;
				    //Checks for email addresses that start with
				    //www. and prints a message if it does.
				    p = Pattern.compile("^www\\.");
				    m = p.matcher(txtEmail.getText());
				    if (m.find()){
				    	String str="Email addresses don't start with \"www.\", only web pages do.";
				    	AutoDialogMessegaes.displayErrorMsg("Email", str, shell);
				    	correct=false;
				    }else
				    	correct=true;
				    p = Pattern.compile(".+@.+\\.[a-z]+");
				    m = p.matcher(txtEmail.getText());
				    
				    if (!correct || !m.find()){
				    	txtEmail.setFocus();
				    	txtEmail.setForeground(SWTResourceManager.getColor(255, 0, 0));
				    }else
				    	txtEmail.setForeground(SWTResourceManager.getColor(0, 0, 0));
				}	    	
			}
		});
		txtEmail.setVisible(false);
		final GridData gd_txtEmail = new GridData(SWT.FILL, SWT.CENTER, true, false);
		txtEmail.setLayoutData(gd_txtEmail);
		//
		return container;
	}

	/**
	 * Create contents of the button bar
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
				true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				IDialogConstants.CANCEL_LABEL, false);
	}

	/**
	 * Return the initial size of the dialog
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(357, 193);
	}
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("Login");
	}
	protected void buttonPressed(int buttonId) {
		if (buttonId == IDialogConstants.OK_ID){
			if (newUser){
				if (!txtPassword.getText().equals(txtRetypePassword.getText())){
					AutoDialogMessegaes.displayFeedbackMsg("Password", "The password is incorrect.", shell);
					return;
				}
				if (txtUsername.getText().indexOf("guest")>=0){
					AutoDialogMessegaes.displayFeedbackMsg("Username", "The username can't include the word 'guest'.", shell);
					txtUsername.setFocus();
					txtUsername.setText("");
					return;
				}
				AddNewUserMsg msg = new AddNewUserMsg(txtUsername.getText(), txtPassword.getText(), txtEmail.getText());
				Client.sendMsg(msg);
				NetworkMsg receivedMsg  = Client.getClientMsg();
				if (receivedMsg.getType()==Type.Error){
					AutoDialogMessegaes.displayErrorMsg("Password error", ((ErrorMsg)receivedMsg).getError(), shell);
					RiskGUI.setUsername("");
					RiskGUI.setUserInDB(false);
					RiskGUI.setUsernameProperties("");
					txtUsername.setText("");
					txtPassword.setText("");
					txtRetypePassword.setText("");
					txtEmail.setVisible(true);
					emailLabel.setVisible(true);
					txtUsername.setFocus();
				}
				else{
					newUser=false;
					txtRetypePassword.setVisible(false);
					retypePasswordLabel.setVisible(false);
					txtEmail.setVisible(false);
					emailLabel.setVisible(false);
					RiskGUI.setUsername(txtUsername.getText());
					RiskGUI.setUserInDB(true);
					super.buttonPressed(buttonId);
				}
			}
			else{
				if (txtUsername.getText()!=""){
					if (txtPassword.getText()==""){
						if (MessageDialog.openConfirm(shell, "Login", "Do you want to login as guest user?")){
							RiskGUI.setUsername("guest");
							RiskGUI.setUserInDB(false);
							RiskGUI.setUsernameProperties("");
							this.close();
							return;
						}
						else{
							AutoDialogMessegaes.displayFeedbackMsg("Login", "You should enter the password.", shell);
							txtPassword.setFocus();
						}
						return;
					}
					AuthenticateUserMsg authenticateMsg = new AuthenticateUserMsg(txtUsername.getText(), txtPassword.getText());
					Client.sendMsg(authenticateMsg);
					NetworkMsg receivedMsg= Client.getClientMsg();
					if (receivedMsg.getType()==Type.Error){
						if (MessageDialog.openConfirm(shell, "Login", "Incorrect username/password. Do you want add new user?")){
							txtRetypePassword.setVisible(true);
							retypePasswordLabel.setVisible(true);
							txtEmail.setVisible(true);
							emailLabel.setVisible(true);
							txtPassword.setFocus();
							newUser=true;
							RiskGUI.setUsername(txtUsername.toString());
							RiskGUI.setUserInDB(false);
							RiskGUI.setUsernameProperties("");
							window.newItemMenuItem_13.setEnabled(false);
							window.newItemMenuItem_14.setEnabled(false);
							txtPassword.setText("");
							txtRetypePassword.setText("");
							txtEmail.setText("");
						}
						else{
							txtPassword.setText("");
							txtPassword.setFocus();
							/*
							RiskGUI.setUsername("guest");
							RiskGUI.setUserInDB(false);
							RiskGUI.setUsernameProperties("");
							window.newItemMenuItem_13.setEnabled(false);
							window.newItemMenuItem_14.setEnabled(false);
							super.buttonPressed(buttonId);*/
						}
					}
					else{
						RiskGUI.setUsername(txtUsername.getText());
						RiskGUI.setUserInDB(true);
						window.newItemMenuItem_13.setEnabled(true);
						window.newItemMenuItem_14.setEnabled(true);
						//window.setRecordsTable(dbact.getRecordTableString());
						//window.setPlayedPlGames(dbact.getUserPlayedGamesString(txtUsername.getText()));
						//RiskGUI.setUsernameProperties(dbact.getUserProperties(txtUsername.getText()));
						super.buttonPressed(buttonId);
					}
				}
				else{
					window.newItemMenuItem_13.setEnabled(false);
					window.newItemMenuItem_14.setEnabled(false);
					super.buttonPressed(buttonId);
				}
			}
		}
		else if (buttonId == IDialogConstants.CANCEL_ID){
			this.close();
		}
		//super.buttonPressed(buttonId);
	}
}
